import { useEffect } from "react";
import {
  Box3,
  BoxGeometry,
  Mesh,
  MeshStandardMaterial,
  Object3D,
  Vector3,
} from "three";

/**
 * 创建一个边界框几何体
 */
export default function useBoundBox(ref: React.RefObject<Object3D>) {
  useEffect(() => {
    if (!ref.current) return;
    createBoundingBoxMesh(ref.current);
    // 清理函数: 在组件卸载时移除边界框
    return () => {
      if (ref.current) {
        const boundingBoxMesh = ref.current.getObjectByName(
          "boundingBox"
        ) as Mesh;
        if (boundingBoxMesh) {
          if (boundingBoxMesh.material instanceof Array) {
            boundingBoxMesh.material.forEach((mat) => mat.dispose()); // 释放每个材质的内存
          } else {
            boundingBoxMesh.material.dispose(); // 释放单一材质的内存
          }
          boundingBoxMesh.geometry.dispose(); // 释放几何体的内存
        }
      }
    };
  }, [ref]); // 依赖于 ref

  function createBoundingBoxMesh(obj: Object3D) {
    const box = new Box3().setFromObject(obj);
    const size = new Vector3();
    box.getSize(size);

    const geometry = new BoxGeometry(size.x, size.y, size.z);
    const material = new MeshStandardMaterial({
      color: 0xff0000,
      wireframe: true,
    }); // 使用红色线框材料
    const mesh = new Mesh(geometry, material);

    // 设置边界框的位置
    const center = new Vector3();
    box.getCenter(center);
    mesh.position.copy(center);
    mesh.name = "boundingBox";
    ref.current!.add(mesh);
  }
}
